import sys
import os
import time
import csv
'''
冷启动脚本
'''

# App类
class App():
    def __init__(self, packagename):
        self.paceageName = packagename
        self.startTime = 0
        self.content = self.launchApp()

    def launchApp(self):
        # 启动App的方法
        cmd = 'adb shell am start -W -n %s' % self.paceageName
        print(cmd)
        self.content = os.popen(cmd)

    def StopApp(self):
        # 暂停App的方法
        paceageName = (self.paceageName).split('/')[0]
        cmd = 'adb shell am force-stop %s' % paceageName
        print('cmd------>', cmd)
        os.popen(cmd)

    def GetLaunchedTime(self):
        # 获取启动时间的方法
        for line in self.content.readlines():
            if "ThisTime" in line:
                self.startTime = line.split(":")[1]
                break
        return self.startTime


# 控制类
class Controller():
    # run
    # CollectAllData
    # SavaDataToCsv
    def __init__(self, count):
        self.app = App('com.estrongs.android.pop/.view.FileExplorerActivity')
        self.counter = count
        self.alldata = [('timestamp', 'elapsedtime')]

    # 单次测试过程
    def testprocess(self):
        self.app.launchApp()
        elpasedtime = self.app.GetLaunchedTime()  # 耗时
        time.sleep(3)
        self.app.StopApp()
        currenttime = self.getCurrentTime()
        time.sleep(3)
        self.alldata.append((currenttime, elpasedtime))

    # 多次执行测试过程
    def run(self):
        while self.counter > 0:
            self.testprocess()
            time.sleep(3)
            self.counter -= 1

    def getCurrentTime(self):
        # 获取当前的时间戳
        currentTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        return currentTime

    def SavaDataToCSV(self):
        with open('cold_startTime.csv', 'w+') as fp:
            write = csv.writer(fp)
            write.writerows(self.alldata)


if __name__ == '__main__':
    controlle = Controller(10)
    controlle.run()
    controlle.SavaDataToCSV()
